//
//  HYInternetViewController.m
//  SPlayer
//
//  Created by liguoqing on 2023/7/31.
//

#import "HYInternetViewController.h"
#import "HYInternetViewModel.h"
#import "HYWebSiteHeaderView.h"
#import "HYHomeVideoModel.h"
#import "HYOtherVideoListCell.h"
#import <HYUIKit/HYPopMenu.h>
#import "HYInternetHeaderView.h"
#import "HYBDPanFIleListController.h"
#import "HYVideoViewModel.h"
#import "HYAudioRoomViewController.h"
#import "HYVideoRoomViewController.h"
#import "HYAlertActionView.h"
#import "HYPreviewHistoryManager.h"
#import <HYUIKit/HYWKWebViewController.h>

#define kHeaderHeight 40

@interface HYInternetViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) HYInternetViewModel *viewModel;

@property (nonatomic, strong) HYWebSiteHeaderView *headerView;

@property (nonatomic, strong) HYInternetHeaderView *historyHeaderView;

@property (nonatomic, strong) UITextField *textField;

@property (nonatomic, strong) UITableView *tableView;

@end

@implementation HYInternetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationBarView.titleLabel.text = NSLocalizedString(@"最近", nil);
    self.view.backgroundColor = AppBgThemeColor;
//    self.navigationBarView.navagationBarStyle = Right_button_show;
//    [self.navigationBarView.rightButton setImage:[UIImage imageNamed:@"icon_play_mode"] forState:UIControlStateNormal];
    [self configUI];
    [self bindSignal];
    [self loadData];
    [self addRefreshHistroyNotify];
}

- (void)configUI
{
    [self.view addEmptyViewWithPlaceImageName:@"icon_empty_content" placeTitle:NSLocalizedString(@"暂无播放记录", nil)];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.navigationBarView.mas_bottom);
        make.left.right.equalTo(self.view);
        make.bottom.mas_equalTo(-TABLE_BAR_HEIGHT);
    }];
}

- (void)bindSignal
{
    @weakify(self);
    [self.viewModel.updatedContentSignal subscribeNext:^(id x) {
        @strongify(self);
        [self.tableView reloadData];
    }];
    [self.viewModel.refreshSubject subscribeNext:^(id x) {
        @strongify(self);
        [self loadData];
    }];
    [self.viewModel.clickSubject subscribeNext:^(HYInternetItemViewModel *itemVM) {
        @strongify(self);
        NSInteger type = itemVM.type;
        NSString *url = itemVM.url;
        NSString *title = itemVM.title;
        switch (type) {
            case HYInternetType_BaiDu:
            case HYInternetType_Moive:
            case HYInternetType_Music:
            {
                [self jumpWebSiteWithUrl:url webSiteTitle:title];
            }
                break;
            case HYInternetType_BaiDuCloud:
            {
                //先判断是否有accessToken 没有的话去通过简化模式获取token保存token 同时获取用户VIP信息等
                //如果有accessToken的话 每次通过过去用户信息检查accessToken是否失效，失效后清除原来的token和用户信息 简化模式获取token保存token 同时获取用户VIP信息等
                @weakify(self);
                if ([BDPanOauthManager manager].accessToken.length != 0){
                    [[BDPanOauthManager manager] getUserInfo:^(NSString * _Nonnull errorStr) {
                        @strongify(self)
                        if (errorStr.length) {
                            [[BDPanOauthManager manager] disableOauthInfo];
                            [self requestBDToken];
                            return;
                        }
                        HYBDPanFIleListController *fileListVC = [[HYBDPanFIleListController alloc]init];
                        fileListVC.isHome = YES;
                        [self.navigationController pushViewController:fileListVC animated:YES];
                    }];
                }else {
                    [self requestBDToken];
                }
            }
                break;
            default:
                break;
        }
    }];
}

- (void)requestBDToken
{
    @weakify(self);
    NSString *url = [NSString stringWithFormat:@"http://openapi.baidu.com/oauth/2.0/authorize?response_type=token&client_id=%@&redirect_uri=%@&scope=%@&display=mobile",[BDPanOauthManager manager].BDPanOauthAppkey,[BDPanOauthManager manager].BDPanOauthrRedirectURI,[BDPanOauthManager manager].BDPanOauthScope];
    HYWKWebViewController *vc = [[HYWKWebViewController alloc]init];
    vc.hiddenNavigationBar = YES;
    vc.netUrl = url;
    vc.getBDaccessToken = ^(NSString * _Nullable token) {
        @strongify(self);
        [BDPanOauthManager manager].accessToken = token;
        HYBDPanFIleListController *fileListVC = [[HYBDPanFIleListController alloc]init];
        fileListVC.isHome = YES;
        [self.navigationController pushViewController:fileListVC animated:YES];
    };
    [self presentViewController:vc animated:YES completion:nil];
}
- (void)loadData
{
    // 刷新播放记录
    [self.viewModel reloadHistoryRecord];
}

- (void)addRefreshHistroyNotify
{
    [kNotificationCenter addObserver:self selector:@selector(loadData) name:kHistroyRefreshListNotification object:nil];
}

- (void)jumpWebSiteWithUrl:(NSString *)url webSiteTitle:(NSString *)siteTitle
{
    HYWKWebViewController *webVC = [[HYWKWebViewController alloc]init];
    webVC.netUrl = url;
    webVC.staticNavTitle = siteTitle;
    [self.navigationController pushViewController:webVC animated:YES];
}

#pragma mark - UITableViewCellDelegate && UITableViewCellDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger row = [self.viewModel numberOfItemsIsHeader:NO];
    tableView.hidden = !row;
    return row;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HYOtherVideoListCell *videoCell = [tableView dequeueReusableCellWithIdentifier:@"HYOtherVideoListCell" forIndexPath:indexPath];
    [videoCell bindViewModel:[self.viewModel cellForRowAtIndexPath:indexPath isHeader:NO]];
    return videoCell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    @weakify(self);
    [HYPreviewHistoryManager playCurrentHistoryWithIndex:indexPath.row jump:^(BOOL isAudio, HYVideoViewModel * _Nonnull viewModel) {
        @strongify(self);
        [self showVideoRoomWithViewModel:viewModel isAudio:isAudio];
    }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kItemListHeight+20;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    @weakify(self);
    if(editingStyle == UITableViewCellEditingStyleDelete){
        [HYPreviewHistoryManager removeCurrentHistoyWithIndex:indexPath.row resultBlock:^{
            @strongify(self);
            [self.viewModel removeCurrenHistoryAtIndexPath:indexPath];
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        }];
    }
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    HYInternetHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"HYInternetHeaderView"];
    headerView.headerTitle = [self.viewModel headerTitleForHeaderInSection:section];
    if(section == 0){
        @weakify(self);
        [headerView clearPreviewHistoryRecordBlok:^{
            @strongify(self);
            [self clearPreviewHistoryTip];
        }];
    }
    headerView.isHiddenDelete = self.viewModel.isHiddenDelete;
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return kHeaderHeight;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}

#pragma mark - 跳转音视频播放器
- (void)showVideoRoomWithViewModel:(HYVideoViewModel *)viewModel isAudio:(BOOL)isAudio
{
    if(viewModel){
        if(isAudio){
            HYAudioRoomViewController *videoRoomVC = [[HYAudioRoomViewController alloc]initWithViewModel:viewModel];
            [self.navigationController pushViewController:videoRoomVC animated:YES];
        }else{
            HYVideoRoomViewController *videoRoomVC = [[HYVideoRoomViewController alloc]initWithViewModel:viewModel];
            [self.navigationController pushViewController:videoRoomVC animated:YES];
        }
    }else{
        [HYHub showMessage:NSLocalizedString(@"未获取到视频信息",nil)];
    }
}

- (void)clearPreviewHistoryTip
{
    @weakify(self);
    [HYAlertActionView showViewControler:self title:NSLocalizedString(@"温馨提示", nil) message:NSLocalizedString(@"是否清空最近播放记录！", nil) actionTitle:@[NSLocalizedString(@"确定", nil),NSLocalizedString(@"取消", nil)] sureBlock:^{
        @strongify(self);
        if([HYPreviewHistoryManager clearAllPlayHistory]){
            [self.viewModel.refreshSubject sendNext:nil];
        }
    } cancelBlock:nil];
}

#pragma mark - loadLazy

- (HYInternetViewModel *)viewModel
{
    if(!_viewModel){
        _viewModel = [[HYInternetViewModel alloc]init];
    }
    return _viewModel;
}

- (HYWebSiteHeaderView *)headerView
{
    if(!_headerView){
        _headerView = [[HYWebSiteHeaderView alloc]initWithViewModel:self.viewModel];
    }
    return _headerView;
}

- (UITableView *)tableView
{
    if(!_tableView){
        _tableView = [[UITableView alloc]init];
        _tableView.backgroundColor = AppBgThemeColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        [_tableView registerClass:[HYInternetHeaderView class] forHeaderFooterViewReuseIdentifier:@"HYInternetHeaderView"];
        [_tableView registerClass:[HYOtherVideoListCell class] forCellReuseIdentifier:@"HYOtherVideoListCell"];
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
    }
    return _tableView;
}


@end
